package com.pjmike.common.util.thread;

import com.pjmike.common.controller.TestController;
import com.pjmike.common.service.TestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

@Component
public class MyFutureTask {

    private static final Logger log= LoggerFactory.getLogger(MyFutureTask.class);


    @Autowired
    private TestService testService;


    private static ExecutorService executor=new ThreadPoolExecutor(8,20,30, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(10),new ThreadPoolExecutor.CallerRunsPolicy());


    public long getUserAggregatedResult(final Long userId){

        log.info("MyFutureTask的线程:" + Thread.currentThread());
        long fansCount = 0, msgCount = 0, collectCount = 0,
                followCount = 0, redBagCount = 0, couponCount = 0;

//        fansCount = testService.countFansCountByUserId(userId);
//        msgCount = testService.countMsgCountByUserId(userId);
//        collectCount = testService.countCollectCountByUserId(userId);
//        followCount = testService.countFollowCountByUserId(userId);
//        redBagCount = testService.countRedBagCountByUserId(userId);
//        couponCount = testService.countCouponCountByUserId(userId);

        try{
            Future<Long> fansCountFT = executor.submit(() -> testService.countFansCountByUserId(userId));
            Future<Long> msgCountFT = executor.submit(() -> testService.countMsgCountByUserId(userId));
            Future<Long> collectCountFT = executor.submit(() -> testService.countCollectCountByUserId(userId));
            Future<Long> followCountFT = executor.submit(() -> testService.countFollowCountByUserId(userId));
            Future<Long> redBagCountFT = executor.submit(() -> testService.countRedBagCountByUserId(userId));
            Future<Long> couponCountFT = executor.submit(() -> testService.countCouponCountByUserId(userId));
            //get阻塞
            fansCount = fansCountFT.get();
            msgCount = msgCountFT.get();
            collectCount = collectCountFT.get();
            followCount = followCountFT.get();
            redBagCount = redBagCountFT.get();
            couponCount = couponCountFT.get();
        }catch (Exception e){
            e.printStackTrace();
            log.error(">>>>>>聚合查询用户聚合信息异常:" + e + "<<<<<<<<<");
        }
        return fansCount + msgCount + collectCount + followCount + redBagCount + couponCount;
    }

}
